package com.miaosha.ms_04.controller;

import com.miaosha.ms_04.domain.User;
import com.miaosha.ms_04.exception.GlobalException;
import com.miaosha.ms_04.result.CodeMsg;
import com.miaosha.ms_04.service.GoodsService;
import com.miaosha.ms_04.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;

/**
 * @Description //TODO
 * @Author Administrator
 * @DATE 2020/9/18 19:13
 **/
@RequestMapping("/goods")
@Controller
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @RequestMapping("/to_list")
    public String list(Model model, User user) {
        List<GoodsVo> goodsList = goodsService.listGoodsVo();
        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsList);
        return "goods_list";
    }

    @RequestMapping("/to_detail/{goodsId}")
    public String getById(Model model, @PathVariable("goodsId") Long goodsId) {
        GoodsVo goodsVo = goodsService.getGoodsById(goodsId);
        if(goodsVo == null){
            throw new GlobalException(CodeMsg.GOOD_NOT_EXIST);
        }
        //倒计时状态 和 剩余时间
        int remainSeconds = 0;
        int miaoshaStatus = 0;//0-还没开始 1- 进行中 2-已结束
        long startTime = goodsVo.getStartDate().getTime();
        long endTime = goodsVo.getEndDate().getTime();
        long now = System.currentTimeMillis();
        if (endTime < now) {
            //已经结束
            remainSeconds = -1;
            miaoshaStatus = 2;
        } else if (startTime > now) {
            //还没开始
            remainSeconds = (int)(startTime - now) * 1000;
            miaoshaStatus = 0;
        } else {
            miaoshaStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("miaoshaStatus", miaoshaStatus);
        model.addAttribute("goods", goodsVo);
        return "goods_detail";
    }


}
